<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select v-model="instruction.fundAccountCode" size="mini" @change="handleFundAccountCodeChange">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select disabled size="mini" v-model="instruction.businClass">
                            <el-option label="银行间业务" value="2"> </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="委托方向:">
                        <el-select v-model="instruction.orderDirection" size="mini" :class="['font-color-' + textColor]">
                            <el-option value="5" label="融资回购" style="color: red">融资回购 </el-option>
                            <el-option value="6" label="融券回购" style="color: #1c8d1c">融券回购 </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="首次结算日期"
                        ><el-date-picker
                            v-model="instruction.firstSettleDate"
                            @change="handleFirstSettleDateChange"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            placeholder="请选择"
                            style="width: 100%"
                        ></el-date-picker
                    ></el-form-item>
                    <el-form-item label="到期结算日期"
                        ><el-date-picker
                            v-model="instruction.endSettleDate"
                            @change="handleEndSettleDateChange"
                            :picker-options="pickerOptions"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            size="mini"
                            placeholder="请选择"
                            style="width: 100%"
                        ></el-date-picker
                    ></el-form-item>
                    <el-form-item label="回购利率:" v-if="isBatchFund">
                        <RiskInputNumber
                            :input="instruction.orderRate"
                            :inputAfter="'%'"
                            :colorStyle="textColor"
                            :precision="5"
                            :field="'orderRate'"
                            :maxlength="15"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="回购金额:" v-if="isBatchFund">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="orderBalance"
                            :inputAfter="'万元'"
                            :colorStyle="textColor"
                            :precision="4"
                            :field="'orderBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="交易对手:" v-if="isBatchStock">
                        <el-select
                            id="multiAndSearch"
                            v-model="instruction.opponentCode"
                            filterable
                            clearable
                            remote
                            :remote-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="changeSelect"
                        >
                            <el-option
                                v-for="i in opponentCodeSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="回购利率:" v-if="isBatchStock">
                        <RiskInputNumber
                            :input="instruction.orderRate"
                            :inputAfter="'%'"
                            :colorStyle="textColor"
                            :precision="5"
                            :field="'orderRate'"
                            :maxlength="15"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="回购金额:" v-if="isBatchStock">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="orderBalance"
                            :inputAfter="'万元'"
                            :colorStyle="textColor"
                            :precision="4"
                            :field="'orderBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="清算速度:">
                        <el-select size="mini" v-model="instruction.clearSpeed" @change="handleClearSpeedChange" :class="['font-color-' + textColor]">
                            <el-option v-for="i in clearSpeedSelectData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="回购天数:">
                        <RiskInputNumber
                            :input="instruction.repoDay"
                            :inputAfter="'天'"
                            :precision="0"
                            :field="'repoDay'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="实际占款天数:">
                        <RiskInputNumber
                            :input="instruction.factUseMoney"
                            :inputAfter="'天'"
                            :precision="0"
                            :disabled="true"
                            :field="'factUseMoney'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="应计利息:">
                        <RiskInputNumber
                            :input="shouldInterest"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :disabled="true"
                            :field="'shouldInterest'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="到期购回金额:">
                        <RiskInputNumber
                            :input="expirePayBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :field="'expirePayBalance'"
                            :disabled="true"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="交易对手:" v-if="isBatchFund">
                        <el-select
                            id="multiAndSearch"
                            v-model="instruction.opponentCode"
                            filterable
                            clearable
                            remote
                            :remote-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="changeSelect"
                        >
                            <el-option
                                v-for="i in opponentCodeSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import moment from 'moment';
import { PrefixInteger, formatInput, highlightColor } from '@/utils/tools';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { getSystemTradeDay } from '@/pages/risk-time/api';
@Component({
    name: 'BankBuybackForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 银行间回购
export default class BankBuybackForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    renderCount: number;
    @Prop()
    stockInfoCache: any;
    @Prop()
    notMesh: boolean;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多基金指令
    Invest: any = new Invest();
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据

    allStockType: any[] = [];
    allOrderDirection: any[] = [];
    orderDirectionSelectData: any[] = [
        { dictKey: '5', dictKeyName: '融资回购' },
        { dictKey: '6', dictKeyName: '融券回购' },
    ]; // 订单方向下拉框数据
    investTypeSelectData: any[] = []; // 投资类型下拉框数据
    clearSpeedSelectData: any[] = []; // 清算速度下拉数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    tradeDays: any[] = []; // 交易日
    stockInfo: any = {};
    textColor: string = '';

    precision: number = 2;
    orderBalance: string = '';

    pickerOptions: any = {
        disabledDate(time) {
            return time.getTime() < Date.now() - 1 * 24 * 3600 * 1000;
        },
    };

    private businessTypeData = [
        {
            label: '银行间业务',
            value: '2',
        },
    ];

    instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        marketCode: '',
        orderDirection: '5', // 委托方向
        stockCode: '', // 证券代码
        endSettleDate: '', // 到期日期
        orderRate: '', // 回购利率
        orderPrice: '',
        repoDay: '', // 回购天数
        orderBalance: '', // 回购金额
        factUseMoney: '', // 实际占款天数
        clearSpeed: '0', // 清算速度
        shouldInterest: '', // 应计利息
        firstSettleDate: moment().format('YYYYMMDD'), // 结算日期
        expirePayBalance: null, // 到期购回金额
        opponentCode: '', // 交易对手
        businClass: '2', // 业务类型
        orderAmount: '', // 指令数量
        orderPriceType: '1',
        investType: '1',
        // orderUser
    };
    shouldInterest: string = '';
    expirePayBalance: string = '';

    // 委托方向对应业务类型数据
    innerOrderDirectionData: any[] = [];

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });

        // 获取投资类型下拉框数据
        this.investTypeSelectData = objToArr(this.Invest.investType);

        // 获取清算速度下拉数据
        this.clearSpeedSelectData = objToArr(this.Invest.clearSpeed);
        this.getOpponentCode('');

        getSystemTradeDay().then(res => {
            this.tradeDays = res.map(item => Number(item)).sort((a, b) => a - b);
        });
        this.changeSelect(false);
    }
    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit('handleSettingValue', this.instruction, '4');
    }

    @Watch('stockInfoCache', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.stockInfoCache) {
            this.stockInfo = this.stockInfoCache;
            // this.orderDirectionSelectData = this.stockInfoCache.tradeDirections;
            // this.getstockCodeList(this.stockInfo.reportCode);
        }
    }

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            instruction.businClass = instruction.businessType;
            this.orderBalance = (Number(instruction.orderBalance) / 10000).toString();
            this.shouldInterest = this.clearNoNum(instruction.shouldInterest);
            this.expirePayBalance = this.clearNoNum(instruction.expirePayBalance);
            this.instruction = JSON.parse(JSON.stringify(instruction));
        }
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instruction.fundCode];
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (this.detail && this.detail.instruction) {
            this.instruction.fundAccountCode = this.detail.instruction.fundAccountCode;
        } else {
            if (newData && newData.length) {
                this.instruction.fundAccountCode = newData[0].fundAccountCode;
            }
        }
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        if (field == 'orderRate') {
            this.handleOrderRateChange(value);
        } else if (field == 'orderBalance') {
            this.handleOrderBalanceChange(value);
        } else if (field == 'repoDay') {
            this.handleRepoDayChange(value);
        }
        // console.log(this.instruction[field], 'value');
    }

    // 更改交易对手方选择框样式
    changeSelect(state: boolean) {
        let obj = document.getElementById('multiAndSearch').parentNode.querySelector('.el-select__caret');
        obj.classList.add('el-icon-arrow-up');
        if (state) {
            obj.classList.add('is-reverse');
        } else {
            obj.classList.remove('is-reverse');
        }
        if (!state) {
            this.getOpponentCode('');
        }
    }

    //   获取交易对手方信息
    private getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        // this.instruction.fundAccountName = fundAccount.fundAccountName;
    }
    handleClearSpeedChange(value: string): void {
        this.instruction.firstSettleDate = this.calcFirstSettleDate(this.instruction).toString();
        this.instruction.endSettleDate = this.calcEndSettleDate(this.instruction).toString();
        this.instruction.factUseMoney = this.calcFactUseMoney(this.instruction);
        this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
        this.shouldInterest = this.clearNoNum(this.instruction.shouldInterest);
        this.expirePayBalance = this.clearNoNum(this.instruction.expirePayBalance);
        if (value === '0') {
            this.instruction.firstSettleDate = moment().format('YYYYMMDD');
        } else {
            this.instruction.firstSettleDate = String(this.tradeDays.find(item => item > Number(moment().format('YYYYMMDD'))));
        }
    }

    handleRepoDayChange(value: string): void {
        if (Number(this.instruction.repoDay) > 366) {
            this.instruction.endSettleDate = '';
            this.instruction.factUseMoney = '';
            this.yh_message_warn('回购天数不能超过366天，请重新输入');
            return;
        }
        this.stockInfo.stockCode = 'R' + PrefixInteger(Number(value || 0), 3) + ' YH';
        this.stockInfo.reportCode = 'R' + PrefixInteger(Number(value || 0), 3);
        this.stockInfo.stockNameSt = value + ' 天回购';
        this.stockInfo.marketCode = '5';
        this.stockInfo.curCode = 'CNY';
        this.stockInfo.curName = '人民币';
        this.instruction.reportCode = this.stockInfo.reportCode;
        this.instruction.marketCode = '5';

        this.$emit('getStockInfo', this.stockInfo);
        if (this.calcEndSettleDate(this.instruction)) {
            this.instruction.endSettleDate = this.calcEndSettleDate(this.instruction).toString();
        }

        this.instruction.factUseMoney = this.calcFactUseMoney(this.instruction);
        this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
        this.shouldInterest = this.clearNoNum(this.instruction.shouldInterest);
        this.expirePayBalance = this.clearNoNum(this.instruction.expirePayBalance);
    }
    handleFirstSettleDateChange(value: string): void {
        this.instruction.endSettleDate = this.calcEndSettleDate(this.instruction).toString();
        this.instruction.factUseMoney = this.calcFactUseMoney(this.instruction);

        this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
        this.shouldInterest = this.clearNoNum(this.instruction.shouldInterest);
        this.expirePayBalance = this.clearNoNum(this.instruction.expirePayBalance);
    }

    handleEndSettleDateChange(value: string): void {
        if (!value) {
            this.instruction.endSettleDate = '';
        }
        this.instruction.factUseMoney = this.calcFactUseMoney(this.instruction);

        this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
        this.shouldInterest = this.clearNoNum(this.instruction.shouldInterest);
        this.expirePayBalance = this.clearNoNum(this.instruction.expirePayBalance);

        // this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        // this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
    }

    /**
     * 回购金额
     *
     * @param value
     */
    handleOrderBalanceChange(value: string): void {
        if (value) {
            let num = formatInput(value, '万元');
            if (!num) {
                this.instruction.orderBalance = '';
                this.yh_message_warn('券面总额超出限定最大金额，请重新输入！');
                return;
            }
            this.instruction.orderBalance = num;
            this.instruction.orderAmount = String(Number(this.instruction.orderBalance) / 100);
            this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
            this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
            this.shouldInterest = this.clearNoNum(this.instruction.shouldInterest);
            this.expirePayBalance = this.clearNoNum(this.instruction.expirePayBalance);
        }
        // this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        // this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
    }

    handleOrderRateChange(value: string): void {
        this.instruction.orderPrice = value;
        this.instruction.shouldInterest = this.calcShouldInterest(this.instruction);
        this.instruction.expirePayBalance = this.calcExpirePayBalance(this.instruction);
        this.shouldInterest = this.clearNoNum(this.instruction.shouldInterest);
        this.expirePayBalance = this.clearNoNum(this.instruction.expirePayBalance);
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction', { immediate: true, deep: true })
    handleFieldColor() {
        if (this.instruction.orderDirection === '5') {
            this.textColor = highlightColor()[1];
        } else if (this.instruction.orderDirection === '6') {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    /**
     *应计利息计算公式应计利息=回购金额*回购利率/365*实际占款天数
     */
    calcShouldInterest(instruction) {
        let result = String(
            ((Number(instruction.orderBalance || 0) * Number(instruction.orderRate || 0)) / 100 / 365) * Number(instruction.factUseMoney || 0)
        );
        if (result === 'NaN') {
            return '0';
        } else {
            return result;
        }
    }

    /**
     * 小数点后
     */
    clearNoNum(value) {
        if (!value) {
            return value;
        }
        value = String(value);
        value = value.replace(/[^\d.]/g, ''); // 清除“数字”和“.”以外的字符
        if (!value) {
            return '';
        } else {
            try {
                value = parseFloat(value).toFixed(this.precision || 0);
                return value;
            } catch (e) {
                return '';
            }
        }
    }

    /**
     * 到期购回金额计算公式   到期购回金额=回购金额+总应计利息=回购金额+应计利息*回购数量=回购金额+应计利息*(回购金额/面值)
     */
    calcExpirePayBalance(instruction) {
        let result = (Number(instruction.orderBalance || 0) + Number(instruction.shouldInterest || 0)).toString();
        // result = this.
        if (!result) {
            return '0';
        } else {
            return result;
        }
    }
    /**
     * 结算日期计算
     */
    calcFirstSettleDate(instruction) {
        if (instruction.clearSpeed === '0') {
            return moment().format('YYYYMMDD');
        } else {
            return this.tradeDays.find(item => item >= Number(moment().add(1, 'd').format('YYYYMMDD')));
        }
    }
    /**
     * 到期日期计算公式
     */
    calcEndSettleDate(instruction) {
        if (Number(instruction.repoDay || 0) === 0) {
            return instruction.firstSettleDate;
        } else {
            return this.tradeDays.find(
                item => item >= Number(moment(instruction.firstSettleDate, 'YYYYMMDD').add(Number(instruction.repoDay), 'd').format('YYYYMMDD'))
            );
        }
    }
    /**
     * 实际占款天数计算公式   实际占款天数=到期日期-结算日期
     */
    calcFactUseMoney(instruction) {
        if (!instruction.endSettleDate || !instruction.firstSettleDate) {
            return '';
        }
        return moment(instruction.endSettleDate, 'YYYYMMDD').diff(moment(instruction.firstSettleDate, 'YYYYMMDD'), 'days').toString();
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
